package com.apobates.jforum.grief.aurl.utils.defend;

import java.util.ArrayList;
import java.util.List;

/**
 * 多值Assertion
 * 注意: 一个目标只有一条消息, 遇到第一个失败规则即中止校验
 * @param <T> 目标类型
 */
public class MultiAssertion<T> implements Assertion<T>{
    protected final T[] values;

    protected MultiAssertion(T[] values) {
        this.values = values;
    }

    @Override
    public List<AssertResult<T>> asserte(PredicateQueue<T> predicateQueue) {
        List<AssertResult<T>> res=new ArrayList<>(values.length);

        outCycle:for (int index=0;index<values.length;index++) {
            boolean success=true;
            String message="OK";
            String errorLabel="basic";
            T tmpTarget = values[index];
            innerCycle:for (AssertPredicate<T> condition: predicateQueue.getConditions()) {
                if(!condition.predicate(tmpTarget)){
                    message = condition.getError().concat(", 参数:"+index);
                    success = false;
                    errorLabel = condition.getLabel();
                    break innerCycle;
                }
            }

            res.add(new AssertResult<>(tmpTarget, success, message, index, errorLabel));
        }
        return res;
    }

    /**
     * 转为全校验实例
     * @return
     */
    public MultiCompleteAssertion<T> toCompleteInstance(){
        return new MultiCompleteAssertion<>(this.values);
    }
}
